<template>
  <view style="background-color: rgba(246, 247, 249, 1)" @click.stop="viewEvent">
    <u-navbar title="道测AI助手" bgColor="rgba(246, 247, 249, 1)" leftIconSize="0"></u-navbar>
    <view class="history" :style="{ marginTop: netHeight }">
      <view class="header" style="width: 100%" id="Hheader">
        <view class="imagebox">
          <image
            style="width: 100%"
            src="https://assets-dev.shuquan.ren/chat-ai/system/banner/banner1.png"
            mode="widthFix"
          ></image>
          <!-- <view class="title">
            <text>智能AI助手</text>
            <text>我们的AI助手可以帮助您更好的沟通</text>
          </view> -->
        </view>
      </view>
      <view class="btns" id="btns">
        <view class="btn" @click="createChat">
          <image class="btn-icon" src="@/static/images/chat.png" mode="scaleToFill" />
          <text class="btn-text">新的对话</text>
        </view>
        <view class="btn" @click="toNewChat">
          <image class="btn-icon" src="@/static/images/modal.png" mode="scaleToFill" />
          <text class="btn-text">模型角色</text>
        </view>
        <view class="btn" @click="jumpChat">
          <image class="btn-icon" src="@/static/images/vip.png" mode="scaleToFill" />
          <text class="btn-text">聊天记录</text>
        </view>
        <view class="btn" @click="toUserCenter">
          <image class="btn-icon" src="@/static/images/myicon.png" mode="scaleToFill" />
          <text class="btn-text">我的</text>
        </view>
      </view>
      <view class="list-box" id="list-box" v-if="historyList.length == 0 ? false : true">
        <scroll-view
          scroll-y
          :style="{ height: systemHeight + 'px' }"
          refresher-enabled
          refresher-background="rgba(0,0,0,0)"
          @refresherrefresh="refresherrefresh"
          :refresher-triggered="refresh"
        >
          <view class="list">
            <view
              class="item"
              v-for="(item, index) in historyList"
              :key="item.id"
              @click="onItemClick(item, index)"
            >
              <view class="item-title-box">
                <view style="max-width: 600rpx">
                  <view>
                    <u--input
                      style="padding: 0"
                      v-if="activeIndex === item.id && updateVal"
                      :placeholder="item.name"
                      border="bottom"
                      clearable
                      :focus="true"
                      v-model="updateItem"
                      @confirm="(value) => sendUpdate(item, value)"
                      @blur="(value) => sendUpdate(item, value)"
                    ></u--input>
                    <view class="item-title" v-else>
                      {{ item.name }}
                    </view>
                  </view>
                </view>
                <view class="dotPositon">
                  <zb-tooltip
                    content="Bottom Center"
                    :placement="index == 0 ? 'bottom-end' : 'left'"
                    ref="tooltip"
                  >
                    <view slot="content">
                      <view>
                        <view class="itemGruop" @click="setName(item, index)">
                          <u-icon
                            name="edit-pen-fill"
                            color="#fff"
                            style="margin-right: 12rpx"
                          ></u-icon>
                          <text class="icontxt">重命名</text>
                        </view>
                        <u-line margin="20rpx 0 0 0"></u-line>
                        <view class="itemGruop">
                          <u-icon
                            name="share-square"
                            color="#fff"
                            style="margin-right: 12rpx"
                          ></u-icon>
                          <button open-type="share" class="shareBtn" @click="jumpToWeb(item)">
                            转发
                          </button>
                        </view>
                        <u-line margin=" 0 0 20rpx 0"></u-line>
                        <view class="itemGruop" @click.stop="onDeleteItem(item, index)">
                          <u-icon name="trash" color="#fff" style="margin-right: 12rpx"></u-icon>

                          <text class="icontxt">删除</text>
                        </view>
                      </view>
                    </view>
                    <view
                      class="moreDot"
                      @click="closeTip(index, item)"
                      :style="{
                        backgroundColor:
                          activeIndex == index
                            ? 'rgba(209, 218, 255, 1)'
                            : 'rgba(235, 235, 235, 1)',
                      }"
                    >
                      <u-icon
                        name="more-dot-fill"
                        :color="
                          activeIndex == index ? 'rgba(10, 63, 255, 1)' : 'rgba(158, 158, 158, 1)'
                        "
                      ></u-icon>
                    </view>
                  </zb-tooltip>
                </view>
              </view>
              <view class="item-bottom">
                <text class="item-text">{{ item.total }}条对话</text>
                <text class="item-text">{{ item.created_at | date('yyyy-mm-dd hh:MM:ss') }}</text>
              </view>
            </view>
          </view>
        </scroll-view>
      </view>
      <view class="startBtn" v-if="historyList.length !== 0 ? false : true">
        <view class="btn">
          <u-button
            @click="createChat"
            type="primary"
            throttleTime="500"
            style="box-shadow: 0px 1px 8px rgba(10, 63, 255, 0.35); font-size: 32rpx"
            color="rgba(10, 63, 255, 1)"
            shape="circle"
            text="开始聊天"
          ></u-button>
        </view>
      </view>
    </view>

    <u-modal
      :show="showModal"
      :content="content"
      @cancel="showModal = false"
      @confirm="onDeleteConfirm"
      showCancelButton
    ></u-modal>
  </view>
</template>

<script>
import { mapState } from 'vuex'
export default {
  data() {
    return {
      height: 730,
      showModal: false,
      selectItem: {},
      updateVal: false,
      selectIndex: 0,
      updateItem: '',
      refresh: false,
      systemHeight: 0,
      modelList: [],
      netHeight: '84rpx',
    }
  },
  options: {
    styleIsolation: 'shared',
  },
  async created() {
    this.$store.commit('setActiveChatIndex', -1)
    this.modelList = await this.$store.dispatch('IchatModelList')
    this.$store.dispatch('IconversationList', { page: 1, limit: 10 })
    // #ifdef H5
    this.netHeight = '84rpx'
    // #endif
    // #ifdef MP-WEIXIN
    this.netHeight = '180rpx'
    // #endif

    this.$nextTick(() => {
      setTimeout(() => {
        uni
          .createSelectorQuery()
          .in(this)
          .select('#btns')
          .fields(
            {
              size: true,
            },
            (res) => {
              console.log(res)
              this.systemHeight = this.systemHeight - res.height
              // this.rightItemHeight=res.map(item=>{item.height})
            },
          )
          .exec(() => {
            // console.log(this.rightItemHeight)
          })
        uni
          .createSelectorQuery()
          .in(this)
          .select('#Hheader')
          .fields(
            {
              size: true,
            },
            (res) => {
              console.log('------------', res)
              // #ifdef H5
              this.systemHeight = this.systemHeight - res.height + 56
              // #endif
              // #ifdef MP-WEIXIN
              this.systemHeight = this.systemHeight - res.height
              // #endif

              // this.rightItemHeight=res.map(item=>{item.height})
            },
          )
          .exec(() => {
            // console.log(this.rightItemHeight)
          })
        console.log('最后', this.systemHeight)
      })
    })
    uni.getSystemInfo({
      // 先获取它上面两个盒子的大小 然后再减去屏幕高度
      success: (res) => {
        console.log(res.windowHeight)
        if (res.platform == 'windows') {
          this.netHeight = '84rpx'
        }
        this.systemHeight = res.windowHeight - 150
        console.log(res)
      },
    })
  },

  computed: {
    ...mapState({
      activeIndex: (state) => state.chat.activeChatIndex,
      historyList: (state) => state.chatAI.saveconversationList,
      showHistory: (state) => state.chat.showHistory,
    }),
    setting() {
      return this.$store.state.chatAI.settingUserInfo
    },
    content() {
      return `确定要删除聊天记录: ${this.selectItem.name} 吗？`
    },
  },
  watch: {
    showHistory: {
      async handler(val) {
        // #ifdef H5
        if (val && !this.height) {
          uni
            .createSelectorQuery()
            .in(this)
            .select('#list-box')
            .boundingClientRect((data) => {
              this.height = parseInt(data.height) * 2
            })
            .exec()
        }
        // #endif
        if (val) {
          await this.$store.dispatch('IconversationList', { page: 1, limit: 10 })
        }
      },

      immediate: true,
    },
  },
  methods: {
    async createChat() {
      // 拿得到当前用户默认角色 setting
      // 拿得到当前模特列表 modelList

      let tempitem = {}
      if (this.setting == -1) {
        tempitem = this.$store.state.config.roleList[0]
      } else {
        // 也要找那一项
        tempitem = this.modelList.find((item2) => {
          return item2.id == this.setting.default_model_id
        })
      }
      const chat = {
        id: uni.$u.guid(),
        // #ifdef H5
        id: 666,
        // #endif

        title: '新的聊天 - ' + tempitem.name,
        desc: tempitem.desc,
        time: new Date().getTime(),
        generatedTitle: false,
        length: 0,
        modelId: tempitem.id,
        modelName: tempitem.name,
        avatar: tempitem.img || tempitem.avatar_url,
      }
      this.$store.commit('CLEARLIST')
      // 这里就要开始新建会话了
      let tempId = await this.$store.dispatch('IconversationNew', {
        name: chat.title,
        model_id: chat.modelId,
      })
      this.$store.commit('SETSHARENAMENAME', chat.title)
      this.$store.commit('SETSHAREID', tempId.id)
      this.$store.commit('myAddHistoryItem', chat)
      this.$store.commit('SAVECHATLIST', {
        role: 'assistant',
        content: chat.desc,
        status: 'done',
        avatar: chat.avatar,
        tepId: uni.$u.guid(),
      })

      this.$store.commit('setShowHistory', false)
    },
    onItemClick(item, index) {
      console.log('---------------', item)
      this.updateItem = ''
      if (this.updateVal) return

      this.$store.commit('CLEARLIST')
      setTimeout(async () => {
        // 点击了之后首选获取聊天记录
        this.$store.commit('SETSHAREID', item.id)
        this.$store.commit('SETSHARENAMENAME', item.name)

        this.$store.commit('SAVEITEM', item)
        await this.$store.dispatch('IchatMessageList', { conversation_id: item.id })
        this.$store.commit('SETNEWID', item.id)
        this.$store.commit('setActiveChatIndex', index)
        this.$store.commit('setShowHistory', false)
      })
    },
    toUserCenter() {
      uni.navigateTo({
        url: '/pages/user/user-center/user-center',
      })
    },
    toNewChat() {
      // uni.navigateTo({
      //   url: '/pages/share/index?invite=ada&uuid=0189e294-4c40-4a4a-9a58-8fbd85d1e901',
      // })
      uni.navigateTo({
        url: '/pages/new-chat/new-chat',
      })
    },
    onDeleteItem(item, index) {
      this.selectItem = item
      this.selectIndex = index
      this.showModal = true
    },
    async onDeleteConfirm() {
      try {
        await this.$store.dispatch('IconversationDelete', { id: this.selectItem.id })
        uni.showToast({
          title: '删除成功',
          icon: 'none',
        })

        this.$refs.tooltip.forEach((item, index) => {
          item.close()
        })
        await this.$store.dispatch('IconversationList', { page: 1, limit: 10 })
      } catch (error) {
        uni.showToast({
          title: '删除失败',
          icon: 'error',
        })
      }
      this.showModal = false
    },
    updatechange(value) {
      console.log(value)
    },
    setName(item, index1) {
      this.$store.commit('setActiveChatIndex', item.id)
      this.updateVal = true
      this.$refs.tooltip.find((item, index) => {
        if (index1 == index) {
          item.close()
          return
        }
      })
    },
    async sendUpdate(item, value) {
      this.updateVal = false
      this.$store.commit('setActiveChatIndex', -1)
      console.log(value)
      if (item.name == value || !value || !this.updateVal) return
      this.updateVal = false
      await this.$store.dispatch('IconversationUpdate', {
        id: item.id,
        name: value,
      })
      await this.$store.dispatch('IconversationList', { page: 1, limit: 10 })
      // 修改
    },
    jumpChat() {
      uni.navigateTo({
        url: '/pages/chatList/index',
      })
    },
    closeTip(index1, item) {
      this.$store.commit('setActiveChatIndex', index1)
      this.$refs.tooltip.forEach((item, index) => {
        if (index1 !== index) {
          item.close()
        }
      })
    },
    async refresherrefresh(e) {
      this.refresh = true
      await this.$store.dispatch('IconversationList', { page: 1, limit: 10 })
      uni.showToast({
        title: '刷新成功',
        icon: 'none',
        duration: 1000,
      })
      this.refresh = false
      console.log(e, '触发')
    },
    viewEvent() {
      if (this.activeIndex < 0) return
      this.$refs.tooltip.forEach((item) => {
        item.close()
      })
      this.$store.commit('setActiveChatIndex', -1)
    },
    async jumpToWeb(item) {
      this.$store.commit('SETSHARENAMENAME', item.name)
      this.$store.commit('SETHISTORY', {
        name: item.name,
        id: item.id,
      })
      // await this.$store.dispatch('IchatShareNew', item.id)
      if (this.activeIndex < 0) return
      this.$refs.tooltip.forEach((item) => {
        item.close()
      })
      this.$store.commit('setActiveChatIndex', -1)
    },
  },
}
</script>

<style scoped lang="scss">
.history {
  width: 750rpx;
  height: 100vh;
  max-height: 100vh;
  padding: 20rpx 32rpx 40rpx 32rpx;
  display: flex;
  flex-direction: column;
  box-sizing: border-box;
  background: rgba(246, 247, 249, 1);
  .shareBtn {
    margin-left: 12rpx;
    color: #fff;
    font-size: 28rpx;
    border: none;
    border-radius: none;
    padding: 0 !important;
    // margin: 0 !important;
    line-height: none;
    background: none;
  }
  .dotPositon {
    position: absolute;
    top: 0;
    right: 0;
    .itemGruop {
      width: 128rpx;
      display: flex;
      // padding-left: 10rpx;
      box-sizing: border-box;
      justify-content: left;
      font-size: 28rpx;
      .icontxt {
        margin-left: 10rpx;
      }
    }
    .moreDot {
      color: rgba(158, 158, 158, 1);
      border-radius: 0px 20rpx 0px 20rpx;
      background: rgba(235, 235, 235, 1);
      width: 44rpx;
      height: 44rpx;
      display: flex;
      align-items: center;
      justify-content: center;
    }
  }
  .header {
    padding: 0;
    margin: 0;
    padding: 0rpx 0 32rpx 0;
    position: relative;

    .imagebox {
      width: 100%;
      height: 348rpx;
      // background-image: url('https://assets-dev.shuquan.ren/chat-ai/system/banner/banner1.png');
      // background-image: url("../../../static/images/homeBg.png");
      background-repeat: no-repeat;
      background-size: 100%;
      object-fit: cover;
      background-position: left 0px top -92rpx;
      border-radius: 19rpx;
      overflow: hidden;

      .title {
        width: 100%;
        height: 100%;
        background-color: rgb(0, 0, 0, 0.3);
        display: flex;
        justify-content: center;
        align-items: center;
        flex-direction: column;
        color: #fff;

        & text:nth-child(1) {
          font-size: 40rpx;
          font-weight: 900;
        }

        & text:nth-child(2) {
          margin-top: 6rpx;
          font-size: 22rpx;
          color: rgba(255, 255, 255, 0.8);
        }
      }
    }

    .image {
      border-radius: 20rpx;
      width: 100%;
    }

    .logo {
      position: absolute;
      right: 0;
      top: 36rpx;
      /* #ifdef MP-WEIXIN */
      display: none;
      /* #endif */
      width: 100rpx;
      height: 100rpx;
      opacity: 0.5;
    }
  }

  .btns {
    display: flex;
    justify-content: space-between;
    align-items: center;
    gap: 16rpx;
    height: 176rpx;
    // box-shadow: 4px 2rpx 4rpx 4px rgb(0, 0, 0, 0.05);
    border-radius: 10rpx;

    // background-color: #fff;

    // & .btn:first-child {
    //   .btn-icon {
    //     filter: invert(0.3) !important;
    //   }
    // }

    .btn {
      flex: 1;
      height: 176rpx;
      border-radius: 20rpx;
      display: flex;
      justify-content: center;
      flex-direction: column;
      align-items: center;
      background-color: #fff;

      .btn-icon {
        border-radius: 50%;
        // background-color: #fefefc;
        height: 56rpx;
        width: 56rpx;
        margin-bottom: 16rpx;
      }
    }

    .btn-text {
      font-size: 28rpx;
      font-weight: 500;
      color: #333;
    }
  }

  .list-box {
    flex: 1;
    width: 100%;
    margin-top: 40rpx;
  }

  .startBtn {
    width: 100%;
    height: 100%;
    text-align: center;
    background-image: url('../../../static/images/empty.png');
    background-repeat: no-repeat;
    background-size: 60%;
    background-position: center 60rpx;
    display: flex;
    justify-content: center;

    .btn {
      width: 264rpx;
      margin-top: 340rpx;

      ::v-deep .u-button {
        box-shadow: 0px 1px 8px rgba(10, 63, 255, 0.35);
      }
    }
  }

  .item {
    padding: 21rpx 28rpx;
    background: #fff;
    margin-bottom: 20rpx;
    border-radius: 20rpx;
    position: relative;

    .clostBtn {
      position: absolute;
      top: 0;
      right: 0;
      color: rgba(158, 158, 158, 1);
      border-radius: 0px 20rpx 0px 20rpx;
      background: rgba(235, 235, 235, 1);
      width: 44rpx;
      height: 44rpx;
      display: flex;
      align-items: center;
      justify-content: center;
    }

    .item-title-box {
      display: flex;
      justify-content: left;

      .item-title {
        font-size: 32rpx;
        font-weight: 700;
        // flex: 1;
        color: rgba(51, 51, 51, 1);
        margin-right: 28rpx;
      }
    }

    .item-bottom {
      display: flex;
      justify-content: space-between;
      margin-top: 16rpx;

      .item-text {
        color: rgb(166, 166, 166);
        font-size: 24rpx;
      }
    }
  }

  .active-item {
    border: 4rpx solid rgba($main-color, 0.9);
  }
}
</style>
